import { useState } from "react";
import KanbanColumn from "./KanbanColumn";

const COLUMN_KEY_TODO = "todo";
const COLUMN_KEY_ONGOING = "ongoing";
const COLUMN_KEY_DONE = "done";

export default function KanbanBoard({
  isLoading,
  todoList,
  ongoingList,
  doneList,
  onAdd,
  onRemove
}) {
  const [draggedItem, setDraggedItem] = useState(null)
  const [dragSource, setDragSource] = useState(null)
  const [dragTarget, setDragTarget] = useState(null)

  const handleDrop = (evt) => {
    if (!draggedItem || !dragSource || !dragTarget || dragSource === dragTarget) {
      return
    }
    dragSource && onRemove(dragSource,draggedItem)
    dragTarget && onRemove(dragTarget,draggedItem)

  }
  return (
    <main className="kanban-board">
      {isLoading ? (<KanbanColumn title="读取中。。。" />) :
        (<>
          <KanbanColumn className='column-todo'
            canAddNew
            onAdd={onAdd.bind(null,COLUMN_KEY_TODO)}
            title="待处理"
            setDraggedItem={setDraggedItem}
            setIsDragSource={(isSrc) => setDragSource(isSrc ? COLUMN_KEY_TODO : null)}
            setIsDragTarget={(isTgt) => setDragTarget(isTgt ? COLUMN_KEY_TODO : null)}
            onDrop={handleDrop}
            cardList={todoList} />
          <KanbanColumn className='column-ongoing'
            title="进行中"
            canAddNew
            onAdd={onAdd.bind(null,COLUMN_KEY_ONGOING)}
            setDraggedItem={setDraggedItem}
            setIsDragSource={(isSrc) => setDragSource(isSrc ? COLUMN_KEY_ONGOING : null)}
            setIsDragTarget={(isTgt) => setDragTarget(isTgt ? COLUMN_KEY_ONGOING : null)}
            onDrop={handleDrop}
            cardList={ongoingList} />
          <KanbanColumn className='column-done'
            title="已完成"
            canAddNew
            onAdd={onAdd.bind(null,COLUMN_KEY_DONE)}
            onRemove={onRemove.bind(null, COLUMN_KEY_DONE)}
            setDraggedItem={setDraggedItem}
            setIsDragSource={(isSrc) => setDragSource(isSrc ? COLUMN_KEY_DONE : null)}
            setIsDragTarget={(isTgt) => setDragTarget(isTgt ? COLUMN_KEY_DONE : null)}
            cardList={doneList}
            onDrop={handleDrop} />
        </>)}
    </main>
  );
}
